<template>
  <div>
    <div class="heatmap-container">
      <!-- Control Panel -->
      <div class="control-panel elevation-6">
        <div class="subtitle-2 font-weight-bold section-title">Location</div>
        <v-row dense>
          <v-col cols="12" sm="6">
            <v-text-field 
              v-model.number="lat" 
              type="number" 
              step="0.000001" 
              label="Latitude" 
              dense 
              outlined 
              hide-details 
            />
          </v-col>
          <v-col cols="12" sm="6">
            <v-text-field 
              v-model.number="lng" 
              type="number" 
              step="0.000001" 
              label="Longitude" 
              dense 
              outlined 
              hide-details 
            />
          </v-col>
        </v-row>
        
        <div class="subtitle-2 font-weight-bold section-title">Year Selection</div>
        <v-row dense>
          <v-col cols="12" sm="6">
            <v-select
              v-model="selectedYear"
              :items="yearOptions"
              label="Select Year"
              dense
              outlined
              hide-details
              @change="onYearChange"
            />
          </v-col>
          <v-col cols="12" sm="6">
            <v-btn 
              color="primary" 
              dark 
              block 
              :disabled="loading" 
              @click="fetchYearData"
            >
              <v-progress-circular 
                v-if="loading" 
                indeterminate 
                size="16" 
                width="2" 
                color="white" 
                class="mr-2" 
              />
              Generate Heatmap
            </v-btn>
          </v-col>
          <v-col cols="12">
            <v-btn 
              color="secondary" 
              outlined 
              block 
              :disabled="loading" 
              @click="useDemoData"
            >
              Use Demo Data
            </v-btn>
          </v-col>
        </v-row>

        <div class="subtitle-2 font-weight-bold section-title">Data Source</div>
        <v-row dense>
          <v-col cols="12">
            <v-select
              v-model="dataSourceId"
              :items="dataSourceOptions"
              label="Data Source"
              dense
              outlined
              hide-details
            />
          </v-col>
        </v-row>

        <!-- Statistics -->
        <div v-if="heatmapData.length > 0" class="stats-section">
          <div class="subtitle-2 font-weight-bold section-title">Statistics</div>
          <v-row dense>
            <v-col cols="6">
              <div class="stat-item">
                <div class="stat-label">Max Daily Output</div>
                <div class="stat-value">{{ maxDailyOutput.toFixed(2) }} kWh</div>
              </div>
            </v-col>
            <v-col cols="6">
              <div class="stat-item">
                <div class="stat-label">Min Daily Output</div>
                <div class="stat-value">{{ minDailyOutput.toFixed(2) }} kWh</div>
              </div>
            </v-col>
            <v-col cols="6">
              <div class="stat-item">
                <div class="stat-label">Average Daily Output</div>
                <div class="stat-value">{{ avgDailyOutput.toFixed(2) }} kWh</div>
              </div>
            </v-col>
            <v-col cols="6">
              <div class="stat-item">
                <div class="stat-label">Total Annual Output</div>
                <div class="stat-value">{{ totalAnnualOutput.toFixed(2) }} kWh</div>
              </div>
            </v-col>
          </v-row>
        </div>
      </div>

      <!-- Heatmap Display Area -->
      <div class="heatmap-display">
        <div v-if="loading" class="loading-overlay">
          <v-progress-circular indeterminate size="64" color="primary"></v-progress-circular>
          <div class="mt-4">Loading solar energy data...</div>
        </div>
        
        <div v-else-if="heatmapData.length > 0" class="heatmap-content">
          <div class="heatmap-title">
            <h3>Solar Energy Output Heatmap - {{ selectedYear }}</h3>
            <div class="heatmap-subtitle">
              Daily solar energy output (kWh) - Red indicates higher output, Green indicates lower output
            </div>
          </div>
          
          <div class="heatmap-grid">
            <div 
              v-for="(day, index) in heatmapData" 
              :key="index"
              class="heatmap-cell"
              :style="{ 
                backgroundColor: getHeatmapColor(day.value),
                opacity: day.value > 0 ? 0.8 : 0.3
              }"
              :title="`Day ${index + 1}: ${day.value.toFixed(2)} kWh`"
            >
              <div class="cell-value">{{ day.value.toFixed(1) }}</div>
            </div>
          </div>
          
          <!-- Legend -->
          <div class="heatmap-legend">
            <div class="legend-title">Output Range (kWh)</div>
            <div class="legend-gradient">
              <div class="legend-labels">
                <span>{{ minDailyOutput.toFixed(1) }}</span>
                <span>{{ maxDailyOutput.toFixed(1) }}</span>
              </div>
              <div class="gradient-bar"></div>
            </div>
          </div>
        </div>
        
        <div v-else class="empty-state">
          <v-icon size="64" color="grey lighten-1">mdi-chart-line</v-icon>
          <div class="mt-4 text-h6 grey--text">No data available</div>
          <div class="mt-2 grey--text">Select a year and location to generate the heatmap</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'HeatmapDashboard',
  data() {
    return {
      // Location information
      lat: 24.4539, // Abu Dhabi
      lng: 54.3773,
      
      // Year selection
      selectedYear: new Date().getFullYear(),
      yearOptions: [],
      
      // Data source
      dataSourceId: '1',
      dataSourceOptions: [
        { text: 'Data Source 1', value: '1' },
        { text: 'Data Source 2', value: '2' },
        { text: 'Data Source 3', value: '3' }
      ],
      
      // Data state
      loading: false,
      heatmapData: [],
      
      // Statistics data
      maxDailyOutput: 0,
      minDailyOutput: 0,
      avgDailyOutput: 0,
      totalAnnualOutput: 0
    }
  },
  
  mounted() {
    this.generateYearOptions()
  },
  
  methods: {
    generateYearOptions() {
      const currentYear = new Date().getFullYear()
      this.yearOptions = []
      for (let year = currentYear - 5; year <= currentYear + 1; year++) {
        this.yearOptions.push(year)
      }
    },
    
    onYearChange() {
      this.heatmapData = []
      this.resetStats()
    },
    
    resetStats() {
      this.maxDailyOutput = 0
      this.minDailyOutput = 0
      this.avgDailyOutput = 0
      this.totalAnnualOutput = 0
    },
    
    async fetchYearData() {
      if (!this.lat || !this.lng) {
        console.error('Please enter valid coordinates')
        return
      }
      
      this.loading = true
      this.heatmapData = []
      this.resetStats()
      
      try {
        const startDate = `${this.selectedYear}-01-01`
        const endDate = `${this.selectedYear}-12-31`
        
        const apiBase = process.env.VUE_APP_API_BASE || 'http://localhost:8080/api'
        const url = `${apiBase}/proxy/solar-energy`
        
        const body = {
          lat: this.lat,
          lng: this.lng,
          start_datetime: `${startDate} 00:00`,
          end_datetime: `${endDate} 23:59`,
          timezone: 4,
          data_source_id: String(this.dataSourceId),
          angle: 45,
          direction: 180,
          rated_power: 200,
          land_form: 'urban',
          temperature_correction_factor: -0.0046,
          module_efficient: 0.13,
          auto_follow_sun: 'stationary',
          reduce_factor: 0.9
        }
        
        const res = await axios.post(url, body)
        const data = res && (res.data || {})
        const result = data.result || {}
        
        if (Array.isArray(result.time) && Array.isArray(result.output) && result.output.length > 0) {
          this.processYearData(result)
          console.log(`Successfully loaded ${result.output[0].length} data points`)
        } else {
          console.error('No data returned for the selected year')
          // Use demo data
          this.useDemoData()
        }
      } catch (error) {
        console.error('Failed to fetch year data:', error)
        console.error('Failed to fetch solar energy data')
        // Use demo data
        this.useDemoData()
      } finally {
        this.loading = false
      }
    },
    
    useDemoData() {
      console.log('Using demo data for testing')
      const daysInYear = this.isLeapYear(this.selectedYear) ? 366 : 365
      const demoData = []
      
      for (let day = 1; day <= daysInYear; day++) {
        // Simulate seasonal changes: high output in summer, low in winter
        const dayOfYear = day
        const seasonalFactor = 0.5 + 0.5 * Math.sin((dayOfYear - 172) * 2 * Math.PI / 365)
        
        // Add some random variation
        const randomFactor = 0.8 + 0.4 * Math.random()
        
        // Base output + seasonal variation + random variation
        const dailyOutput = 100 * seasonalFactor * randomFactor
        
        demoData.push({
          day: day,
          value: Math.max(0, dailyOutput)
        })
      }
      
      this.heatmapData = demoData
      this.calculateStats()
    },
    
    processYearData(result) {
      const times = result.time || []
      const outputs = (result.output && result.output[0]) || []
      
      if (times.length === 0 || outputs.length === 0) {
        console.error('Invalid data format received')
        return
      }
      
      console.log(`Processing ${outputs.length} data points for year ${this.selectedYear}`)
      
      // Group 8760 data points by day (24 data points represent one day)
      const dailyData = []
      const daysInYear = this.isLeapYear(this.selectedYear) ? 366 : 365
      
      for (let day = 0; day < daysInYear; day++) {
        const dayStartIndex = day * 24
        const dayEndIndex = Math.min(dayStartIndex + 24, outputs.length)
        
        if (dayStartIndex < outputs.length) {
          // Calculate total daily output (kWh)
          const dayOutputs = outputs.slice(dayStartIndex, dayEndIndex)
          const dailyTotal = dayOutputs.reduce((sum, output) => sum + (output || 0), 0)
          
          dailyData.push({
            day: day + 1,
            value: dailyTotal
          })
        } else {
          // If data is insufficient, fill with 0
          dailyData.push({
            day: day + 1,
            value: 0
          })
        }
      }
      
      console.log(`Generated ${dailyData.length} daily data points`)
      this.heatmapData = dailyData
      this.calculateStats()
    },
    
    isLeapYear(year) {
      return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)
    },
    
    calculateStats() {
      if (this.heatmapData.length === 0) return
      
      const values = this.heatmapData.map(day => day.value).filter(v => v > 0)
      
      if (values.length > 0) {
        this.maxDailyOutput = Math.max(...values)
        this.minDailyOutput = Math.min(...values)
        this.avgDailyOutput = values.reduce((sum, val) => sum + val, 0) / values.length
        this.totalAnnualOutput = this.heatmapData.reduce((sum, day) => sum + day.value, 0)
      }
    },
    
    getHeatmapColor(value) {
      if (value <= 0) return '#f5f5f5'
      
      // Use more intuitive color scheme: Blue (low) -> Green -> Yellow -> Red (high)
      const maxValue = this.maxDailyOutput || 1
      const ratio = Math.min(value / maxValue, 1)
      
      if (ratio < 0.25) {
        // Blue to green
        const blueRatio = ratio * 4
        const blue = Math.round(255 * (1 - blueRatio))
        const green = Math.round(255 * blueRatio)
        return `rgb(0, ${green}, ${blue})`
      } else if (ratio < 0.5) {
        // Green to yellow
        const greenRatio = (ratio - 0.25) * 4
        const red = Math.round(255 * greenRatio)
        const green = 255
        return `rgb(${red}, ${green}, 0)`
      } else if (ratio < 0.75) {
        // Yellow to orange
        const orangeRatio = (ratio - 0.5) * 4
        const red = 255
        const green = Math.round(255 * (1 - orangeRatio * 0.5))
        return `rgb(${red}, ${green}, 0)`
      } else {
        // Orange to red
        const redRatio = (ratio - 0.75) * 4
        const red = 255
        const green = Math.round(255 * (0.5 - redRatio * 0.5))
        return `rgb(${red}, ${green}, 0)`
      }
    }
  }
}
</script>

<style scoped>
.heatmap-container {
  display: flex;
  height: 100vh;
  background: #f5f5f5;
}

.control-panel {
  width: 350px;
  background: white;
  padding: 20px;
  overflow-y: auto;
  border-right: 1px solid #e0e0e0;
}

.heatmap-display {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  position: relative;
}

.section-title {
  margin-top: 20px;
  margin-bottom: 10px;
  color: #333;
}

.stats-section {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.loading-overlay {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #666;
}

.heatmap-content {
  max-width: 1200px;
  margin: 0 auto;
}

.heatmap-title {
  text-align: center;
  margin-bottom: 30px;
}

.heatmap-title h3 {
  margin: 0;
  color: #333;
}

.heatmap-subtitle {
  color: #666;
  font-size: 14px;
  margin-top: 5px;
}

.heatmap-grid {
  display: grid;
  grid-template-columns: repeat(52, 1fr);
  gap: 1px;
  margin-bottom: 30px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  max-width: 100%;
  overflow-x: auto;
}

.heatmap-cell {
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.heatmap-cell:hover {
  transform: scale(1.1);
  z-index: 10;
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}

.cell-value {
  font-size: 8px;
  font-weight: bold;
  color: #333;
  text-shadow: 0 0 2px white;
}

.heatmap-legend {
  text-align: center;
  margin-top: 20px;
}

.legend-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.legend-gradient {
  display: inline-block;
  width: 300px;
}

.legend-labels {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 12px;
  color: #666;
}

.gradient-bar {
  height: 20px;
  background: linear-gradient(to right, #0000ff, #00ff00, #ffff00, #ff8000, #ff0000);
  border-radius: 4px;
  border: 1px solid #ddd;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #666;
}

@media (max-width: 768px) {
  .heatmap-container {
    flex-direction: column;
  }
  
  .control-panel {
    width: 100%;
    max-height: 300px;
  }
  
  .heatmap-grid {
    grid-template-columns: repeat(26, 1fr);
  }
}
</style>
